package org.xgluo.excle;

import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.IOException;

/**
 * @author LXG
 * @program: JBOToExcle
 * @name: ExcleUtil
 * @description: Excle工具类
 * @date 2024年12月25日
 */
public class ExcleUtil {


    private static final Logger logger = LoggerFactory.getLogger(ExcleUtil.class);

    public static Workbook getWorkBookByType(String url) {
        if (url == null || url.isEmpty()) {
            throw new RuntimeException("文件路径为空");
        }else{
            logger.debug("打开Excle文件：" + url);
        }
       //获取一个文件读取流对象
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(url);
            //定义Exlce写入工具 Workbook
            if (url.endsWith(ExcleConstant.EXCLE_TYPE_XLSX)) {
                return new XSSFWorkbook(fis);
            } else if (url.endsWith(ExcleConstant.EXCLE_TYPE_XLS)) {
                return new HSSFWorkbook(fis);
            } else {
                throw new RuntimeException("无法识别的Excle文件类型");
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                logger.error("关闭文件流失败！");
                logger.error(e.getMessage());
            }
        }
    }

}
